use sea_orm_migration::{prelude::*, schema::*};

#[derive(DeriveMigrationName)]
pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        // 创建`cake`表
        manager
            .create_table(
                Table::create()
                    .table(Cake::Table).comment("蛋糕表")
                    .if_not_exists()
                    // 主键自增
                    // .col(
                    //     ColumnDef::new(Cake::Id)
                    //         .integer()
                    //         .not_null()
                    //         .auto_increment()
                    //         .primary_key(),
                    // )
                    .col(pk_auto(Cake::Id).comment("主键"))
                    .col(string(Cake::Name).comment("蛋糕名称"))
                    .to_owned(),
            )
            .await?;

        // 创建`fruit`表
        manager
            .create_table(
                Table::create()
                    .table(Fruit::Table).comment("水果表")
                    .if_not_exists()
                    // 主键自增
                    .col(pk_auto(Fruit::Id).comment("主键"))
                    .col(string(Fruit::Name).comment("水果名称"))
                    .col(integer(Fruit::CakeId).comment("蛋糕id"))
                    .to_owned(),
            )
            .await?;

        // 创建外键
        manager
            .create_foreign_key(
                ForeignKey::create()
                    // 外键名
                    .name("fk_fruit_cake")
                    // Fruit::CakeId 引用 Cake::Id
                    .from(Fruit::Table, Fruit::CakeId)
                    .to(Cake::Table, Cake::Id)
                    // 级联修改
                    .on_update(ForeignKeyAction::Cascade)
                    // 级联删除
                    .on_delete(ForeignKeyAction::Cascade)
                    .to_owned(),
            )
            .await
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        // Replace the sample below with your own migration scripts

        // 删除外键
        manager
            .drop_foreign_key(ForeignKey::drop().name("fk_fruit_cake").table(Fruit::Table).to_owned())
            .await?;

        // 删除`fruit`表
        manager
            .drop_table(Table::drop().table(Fruit::Table).to_owned())
            .await?;

        // 删除`cake`表
        manager
            .drop_table(Table::drop().table(Cake::Table).to_owned())
            .await
    }
}

#[derive(DeriveIden)]
enum Cake {
    Table, // 映射到表名为`cake`， 其他映射为列名
    Id,
    #[sea_orm(iden = "name")] // 重命名列名(默认snake_case)
    Name,
}

#[derive(DeriveIden)]
enum Fruit {
    Table, // 映射到表名为`fruit`
    Id,
    Name,
    CakeId,
}
